//
//  HttpRequest.m
//  CardsGame
//
//  Created by PSY on 2016/12/8.
//  Copyright © 2016年 myGame. All rights reserved.
//

#import "HttpRequest.h"
#import "LoginViewController.h"

@implementation HttpRequest
#pragma mark -- GET请求 --
+ (void)getWithURLString:(NSString *)URLString
              parameters:(id)parameters
         showProgressHud:(BOOL)show
                 success:(void (^)(NSDictionary *))success
                 failure:(void (^)(NSError *))failure {
    

    /**
     *  请求队列的最大并发数
     */
    //    manager.operationQueue.maxConcurrentOperationCount = 5;
    /**
     *  请求超时的时间
     */
    //    manager.requestSerializer.timeoutInterval = 5;
    if (show) {
        [SVProgressHUD showWithStatus:@"加载中..."];
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    __weak typeof(self)weakSelf = self;
//    __block AFHTTPSessionManager *tools = manager;
//    [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
//        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
//        __autoreleasing NSURLCredential *credential =nil;
//        if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//            if([tools.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
//                credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//                if(credential) {
//                    disposition = NSURLSessionAuthChallengeUseCredential;
//                } else {
//                    disposition =NSURLSessionAuthChallengePerformDefaultHandling;
//                }
//            } else {
//                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
//            }
//        } else {
//            // client authentication
//            SecIdentityRef identity = NULL;
//            SecTrustRef trust = NULL;
//            NSString *p12 = [[NSBundle mainBundle] pathForResource:@"cacert"ofType:@"p12"];
//            NSFileManager *fileManager =[NSFileManager defaultManager];
//
//            if(![fileManager fileExistsAtPath:p12])
//            {
//                NSLog(@"client.p12:not exist");
//            }
//            else
//            {
//                NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
//
//                if ([[weakSelf class] extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])
//                {
//                    SecCertificateRef certificate = NULL;
//                    SecIdentityCopyCertificate(identity, &certificate);
//                    const void*certs[] = {certificate};
//                    CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
//                    credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
//                    disposition =NSURLSessionAuthChallengeUseCredential;
//                }
//            }
//        }
//        *_credential = credential;
//        return disposition;
//    }];
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
    request.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    if ([HFUser getSaveToken].length > 0) {
        [request setValue:[HFUser getSaveToken] forHTTPHeaderField:@"token"];
    }
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (show) {
            [SVProgressHUD dismiss];
        }
        if (!error) {
            if (success) {
                success(responseObject);
            }
        } else {
            if (failure) {
                failure(error);
            }
        }
    }] resume];
}

#pragma mark -- POST请求 --
+ (void)postWithURLString:(NSString *)URLString
               parameters:(id)parameters
          showProgressHud:(BOOL)show
                  success:(void (^)(NSDictionary *))success
                  failure:(void (^)(NSError *))failure
                    login:(void (^)(BOOL))login{
    if (show) {
        [SVProgressHUD showWithStatus:@"加载中..."];
    }

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    __weak typeof(self)weakSelf = self;
//    __block AFHTTPSessionManager *tools = manager;
//    [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
//        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
//        __autoreleasing NSURLCredential *credential =nil;
//        if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//            if([tools.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
//                credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//                if(credential) {
//                    disposition = NSURLSessionAuthChallengeUseCredential;
//                } else {
//                    disposition =NSURLSessionAuthChallengePerformDefaultHandling;
//                }
//            } else {
//                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
//            }
//        } else {
//            // client authentication
//            SecIdentityRef identity = NULL;
//            SecTrustRef trust = NULL;
//            NSString *p12 = [[NSBundle mainBundle] pathForResource:@"cacert"ofType:@"p12"];
//            NSFileManager *fileManager =[NSFileManager defaultManager];
//
//            if(![fileManager fileExistsAtPath:p12])
//            {
//                NSLog(@"client.p12:not exist");
//            }
//            else
//            {
//                NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
//
//                if ([[weakSelf class] extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])
//                {
//                    SecCertificateRef certificate = NULL;
//                    SecIdentityCopyCertificate(identity, &certificate);
//                    const void*certs[] = {certificate};
//                    CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
//                    credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
//                    disposition =NSURLSessionAuthChallengeUseCredential;
//                }
//            }
//        }
//        *_credential = credential;
//        return disposition;
//    }];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
    request.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    if ([HFUser getSaveToken].length > 0) {
        [request setValue:[HFUser getSaveToken] forHTTPHeaderField:@"X-Authentication"];
    }
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (show) {
            [SVProgressHUD dismiss];
        }
        if (!error) {
            NSLog(@"%@%@",responseObject[@"code"],responseObject[@"message"]);
            if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
                if (success) {
                    success(responseObject);
                }
            }
            if ([responseObject[@"code"] integerValue] == 40001) {
                NSMutableURLRequest *unRequest = [[AFJSONRequestSerializer serializer] requestWithMethod:@"GET" URLString:HOST(@"auth/token") parameters:nil error:nil];
                unRequest.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
                //    NSLog(@"=======%@",[HFUser getSaveToken]);
                if ([HFUser getSaveRefreshToken].length > 0) {
                    [unRequest setValue:[HFUser getSaveRefreshToken] forHTTPHeaderField:@"X-Authentication"];
                    [unRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                    [unRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
                    [[manager dataTaskWithRequest:unRequest completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                        if (!error) {
                            if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
                                [HFUser saveToken:responseObject[@"data"][@"token"]];
                                [HFUser saveRefreshToken:responseObject[@"data"][@"refreshToken"]];
                                [HFUser rememberUsername:responseObject[@"data"][@"username"]];
                                dispatch_queue_t xrQueue = dispatch_queue_create("loadImage", NULL); // 创建GCD线程队列
                                dispatch_async(xrQueue, ^{
                                    // 异步下载图片
                                    UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:responseObject[@"data"][@"avatar"]]]];
                                    // 主线程刷新UI
                                    
                                    NSString *path_document = NSHomeDirectory();
                                    //设置一个图片的存储路径
                                    NSString *imagePath = [path_document stringByAppendingString:@"/Documents/icon.png"];
                                    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
                                    [UIImagePNGRepresentation(img) writeToFile:imagePath atomically:YES];
                                    
                                    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
                                    request.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
                                    //    NSLog(@"=======%@",[HFUser getSaveToken]);
                                    if ([HFUser getSaveToken].length > 0) {
                                        [request setValue:[HFUser getSaveToken] forHTTPHeaderField:@"X-Authentication"];
                                    }
                                    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                                    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
                                    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                                        if (!error) {
                                            if (success) {
                                                success(responseObject);
                                            }
                                        }
                                    }]resume];
                                });
                            }else{
                                if (login) {
                                    login(YES);
                                }
                            }
                        }else{
                            NSLog(@"%@",error);
                        }
                    }] resume];
                }else{
                    if (login) {
                        login(YES);
                    }
                }
            }else if([responseObject[@"code"] integerValue] != CODESUCCESS){
                [MyObject failedPrompt1:responseObject[@"message"]];
            }
        } else {
            if (failure) {
                failure(error);
            }
        }
    }] resume];
}
+ (void)postSimWithURLString:(NSString *_Nullable)URLString
                  parameters:(id _Nullable )parameters
             showProgressHud:(BOOL)show
                     success:(void (^_Nullable)(NSDictionary * _Nullable responseObject))success
                     failure:(void (^_Nullable)(NSError * _Nullable error))failure
{
    if (show) {
        [SVProgressHUD showWithStatus:@"加载中..."];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    __weak typeof(self)weakSelf = self;
//    __block AFHTTPSessionManager *tools = manager;
//    [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
//        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
//        __autoreleasing NSURLCredential *credential =nil;
//        if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//            if([tools.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
//                credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//                if(credential) {
//                    disposition = NSURLSessionAuthChallengeUseCredential;
//                } else {
//                    disposition =NSURLSessionAuthChallengePerformDefaultHandling;
//                }
//            } else {
//                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
//            }
//        } else {
//            // client authentication
//            SecIdentityRef identity = NULL;
//            SecTrustRef trust = NULL;
//            NSString *p12 = [[NSBundle mainBundle] pathForResource:@"cacert"ofType:@"p12"];
//            NSFileManager *fileManager =[NSFileManager defaultManager];
//
//            if(![fileManager fileExistsAtPath:p12])
//            {
//                NSLog(@"client.p12:not exist");
//            }
//            else
//            {
//                NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
//
//                if ([[weakSelf class] extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])
//                {
//                    SecCertificateRef certificate = NULL;
//                    SecIdentityCopyCertificate(identity, &certificate);
//                    const void*certs[] = {certificate};
//                    CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
//                    credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
//                    disposition =NSURLSessionAuthChallengeUseCredential;
//                }
//            }
//        }
//        *_credential = credential;
//        return disposition;
//    }];
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
    request.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    //    NSLog(@"=======%@",[HFUser getSaveToken]);
    if ([HFUser getSaveToken].length > 0) {
        [request setValue:[HFUser getSaveToken] forHTTPHeaderField:@"X-Authentication"];
    }
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (show) {
            [SVProgressHUD dismiss];
        }
        if (!error) {
            if (success) {
                success(responseObject);
            }
        } else {
            if (failure) {
                failure(error);
            }
        }
    }] resume];
}

#pragma mark -- POST/GET网络请求 --
+ (void)requestWithURLString:(NSString *)URLString
                  parameters:(id)parameters
             showProgressHud:(BOOL)show
                        type:(HttpRequestType)type
                     success:(void (^)(NSDictionary *))success
                     failure:(void (^)(NSError *))failure {
    if (show) {
        [SVProgressHUD showWithStatus:@"加载中..."];
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    __weak typeof(self)weakSelf = self;
//    __block AFHTTPSessionManager *tools = manager;
//    [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
//        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
//        __autoreleasing NSURLCredential *credential =nil;
//        if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//            if([tools.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
//                credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//                if(credential) {
//                    disposition = NSURLSessionAuthChallengeUseCredential;
//                } else {
//                    disposition =NSURLSessionAuthChallengePerformDefaultHandling;
//                }
//            } else {
//                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
//            }
//        } else {
//            // client authentication
//            SecIdentityRef identity = NULL;
//            SecTrustRef trust = NULL;
//            NSString *p12 = [[NSBundle mainBundle] pathForResource:@"cacert"ofType:@"p12"];
//            NSFileManager *fileManager =[NSFileManager defaultManager];
//
//            if(![fileManager fileExistsAtPath:p12])
//            {
//                NSLog(@"client.p12:not exist");
//            }
//            else
//            {
//                NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
//
//                if ([[weakSelf class] extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])
//                {
//                    SecCertificateRef certificate = NULL;
//                    SecIdentityCopyCertificate(identity, &certificate);
//                    const void*certs[] = {certificate};
//                    CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
//                    credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
//                    disposition =NSURLSessionAuthChallengeUseCredential;
//                }
//            }
//        }
//        *_credential = credential;
//        return disposition;
//    }];
    switch (type) {
        case HttpRequestTypeGet:
        {
            [manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if (show) {
                    [SVProgressHUD dismiss];
                }
                if (success) {
                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    success(dict);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (show) {
                    [SVProgressHUD dismiss];
                }
                if (failure) {
                    failure(error);
                }
            }];
        }
            break;
        case HttpRequestTypePost:
        {
            [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if (show) {
                    [SVProgressHUD dismiss];
                }
                if (success) {
                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    success(dict);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (show) {
                    [SVProgressHUD dismiss];
                }
                if (failure) {
                    failure(error);
                }
            }];
        }
            break;
    }
}

#pragma mark -- 上传图片 --
+ (void)uploadWithURLString:(NSString *)URLString
                 parameters:(id)parameters
            showProgressHud:(BOOL)show
                uploadParam:(UploadParam *)uploadParam
                    success:(void (^)(NSDictionary * _Nullable responseObject))success
                    failure:(void (^)(NSError *))failure {
    if (show) {
        [SVProgressHUD showWithStatus:@"加载中..."];
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    __weak typeof(self)weakSelf = self;
//    __block AFHTTPSessionManager *tools = manager;
//    [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
//        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
//        __autoreleasing NSURLCredential *credential =nil;
//        if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//            if([tools.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
//                credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//                if(credential) {
//                    disposition = NSURLSessionAuthChallengeUseCredential;
//                } else {
//                    disposition =NSURLSessionAuthChallengePerformDefaultHandling;
//                }
//            } else {
//                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
//            }
//        } else {
//            // client authentication
//            SecIdentityRef identity = NULL;
//            SecTrustRef trust = NULL;
//            NSString *p12 = [[NSBundle mainBundle] pathForResource:@"cacert"ofType:@"p12"];
//            NSFileManager *fileManager =[NSFileManager defaultManager];
//
//            if(![fileManager fileExistsAtPath:p12])
//            {
//                NSLog(@"client.p12:not exist");
//            }
//            else
//            {
//                NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
//
//                if ([[weakSelf class] extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])
//                {
//                    SecCertificateRef certificate = NULL;
//                    SecIdentityCopyCertificate(identity, &certificate);
//                    const void*certs[] = {certificate};
//                    CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
//                    credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
//                    disposition =NSURLSessionAuthChallengeUseCredential;
//                }
//            }
//        }
//        *_credential = credential;
//        return disposition;
//    }];

    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.filename mimeType:uploadParam.mimeType];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (show) {
            [SVProgressHUD dismiss];
        }
        if (success) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            success(dict);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (show) {
            [SVProgressHUD dismiss];
        }
        if (failure) {
            failure(error);
        }
    }];
}

//+(BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
//    OSStatus securityError = errSecSuccess;
//    //client certificate password
//    NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"Jinluobo118"
//                                                                 forKey:(__bridge id)kSecImportExportPassphrase];
//    
//    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
//    securityError = SecPKCS12Import((__bridge CFDataRef)inPKCS12Data,(__bridge CFDictionaryRef)optionsDictionary,&items);
//    
//    if(securityError == 0) {
//        CFDictionaryRef myIdentityAndTrust =CFArrayGetValueAtIndex(items,0);
//        const void*tempIdentity =NULL;
//        tempIdentity= CFDictionaryGetValue (myIdentityAndTrust,kSecImportItemIdentity);
//        *outIdentity = (SecIdentityRef)tempIdentity;
//        const void*tempTrust =NULL;
//        tempTrust = CFDictionaryGetValue(myIdentityAndTrust,kSecImportItemTrust);
//        *outTrust = (SecTrustRef)tempTrust;
//    } else {
//        NSLog(@"Failedwith error code %d",(int)securityError);
//        return NO;
//    }
//    return YES;
//}
@end
